﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace EmbeddedSensorCloud.Plugin.Navigation
{
    internal class ResponseCreator
    {
        private readonly SaxParser _Parser;

        private string _CityName, _StreetName;
        private Dictionary<string, HashSet<string>> _OSMData;

        #region Constructor

        public ResponseCreator(string path)
        {
            this._Parser = new SaxParser(path, true, true);
            this._Parser.StartElementAction = StartElement;
            this._Parser.EndElementAction = EndElement;

            this._CityName = this._StreetName = string.Empty;
            this._OSMData = new Dictionary<string, HashSet<string>>();
        }

        #endregion

        public bool ReloadXMLFile()
        {
            if (this._Parser.FinishedWork)
            {
                this._Parser.StartParsing();
                return true;
            }
            return false;
        }

        public string SearchForStreet(string streetName)
        {
            if (this._Parser.FinishedWork)
            {
                StringBuilder answer = new StringBuilder("<h2>Street '" + streetName + "' found in following cities:</h2><ul>");
                foreach (KeyValuePair<string, HashSet<string>> city in this._OSMData)
                {
                    if (city.Value.Contains(streetName))
                    {
                        answer.AppendFormat("<li>{0}</li>", city.Key);
                    }
                }
                answer.Append("</ul>");
                return answer.ToString();
            }
            return "";
        }

        #region SaxParser-Callbacks

        private void StartElement(string name, Dictionary<string, string> attributes)
        {
            if (name == "tag")
            {
                if (attributes["k"] == "addr:city")
                {
                    _CityName = attributes["v"];
                }
                else if (attributes["k"] == "addr:street")
                {
                    _StreetName = attributes["v"];
                }
            }

            if (_CityName != "" && _StreetName != "")
            {
                if (!_OSMData.ContainsKey(_CityName))
                {
                    _OSMData.Add(_CityName, new HashSet<string>());
                }

                if (!_OSMData[_CityName].Contains(_StreetName))
                {
                    _OSMData[_CityName].Add(_StreetName);
                }
            }
        }

        private void EndElement(string name)
        {
            this._CityName = this._StreetName = string.Empty;
        }

        #endregion
    }
}
